
/**
 * 
 */
package com.cqan.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.cqan.account.entity.User;
import com.cqan.exception.AppException;
import com.cqan.system.entity.Attachment;
import com.cqan.system.service.AttachmentService;
import com.cqan.util.encode.EncodeUtils;

/**
 * 附件通用上传模块
 * @author slaton
 * 
 *         下午01:21:21
 */
@Controller
@RequestMapping(value = "/attach")
public class AttachmentController extends CommonUploadController{
	
	private String savepath="attachment";
	private AttachmentService attachmentService;
	
	@ResponseBody
	@RequestMapping(value = "/upload.htm",method=RequestMethod.POST)
	public String upload(HttpServletRequest request) throws  AppException {
		User user = getUserDetails();
		if (user==null) {
			throw new AppException("login.unlogin");
		}
		StringBuffer sb = new StringBuffer();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile attachment = multipartRequest.getFile("attachment"); 
		Attachment att = null;
		if (attachment.isEmpty()) {
			throw new AppException("upload.file");
		}
		String fileName;
		try {
			fileName = attachment.getOriginalFilename();
			List<String> exts = Arrays.asList(allowedSuffix);
			String suffix = null;
			int li = fileName.lastIndexOf(".");
			if (li != -1) {
				suffix = fileName.substring(li, fileName.length());
			}
			if (suffix==null||!exts.contains(suffix.toLowerCase())) {
				throw new AppException("upload.suffix");
			}
			String mdName = EncodeUtils.md5(attachment.getInputStream());
			att = attachmentService.findAttachmentByMd5(mdName);
			if (att!=null&&att.getFileName().equals(fileName)) {
				sb.append("exist=").append(true).append("#").append("id=").append(att.getId());
				return sb.toString();
			}
			if(att!=null){
				att.setFileName(fileName);
				att.setUid(user.getId());
				att.setContentType(att.getContentType());
				att.setEnabled(true);
				att.setCreateTime(Calendar.getInstance().getTime());
				att.setMd5(mdName);
				att.setSize(att.getSize());
				att.setUrl(att.getUrl());
				att.setFrequency(0);
				attachmentService.add(att);
			}else{
				String path = request.getSession().getServletContext().getRealPath("/");
				String saveFilePath = new StringBuffer().append(savepath).append(createSavePath()).toString();
				File tempsaveFile = new File(path+saveFilePath);
				if (!tempsaveFile.exists()) {
					tempsaveFile.mkdirs();
				}
				String url = saveFilePath+mdName+suffix;
				File savefile = new File(path+url);
				Attachment att2 = new Attachment();
				if (!savefile.exists()) {
					FileCopyUtils.copy(attachment.getBytes(), savefile);
					att2.setFileName(fileName);
					att2.setUid(user.getId());
					att2.setContentType(attachment.getContentType());
					att2.setEnabled(true);
					att2.setCreateTime(Calendar.getInstance().getTime());
					att2.setMd5(mdName);
					att2.setSize(attachment.getSize());
					att2.setUrl(url);
					att2.setFrequency(0);
					attachmentService.add(att2);
					sb.append("exist=").append(true).append("#");
				}else {
					sb.append("exist=").append(false).append("#");
				}
				sb.append("id=").append(att2.getId());
				return sb.toString();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new AppException("upload.unknown");
		}
		return sb.toString();
	}

	@RequestMapping(value = "/download.htm", method = RequestMethod.GET)
	public ModelAndView download(Long attid, HttpServletRequest request,
			HttpServletResponse response) throws AppException {
		User user = getUserDetails();
		if (user==null) {
			throw new AppException("login.unlogin");
		}
		if(attid==null){
			throw new AppException("common.param");
		}
		Attachment attachment = attachmentService.get(attid);
		if (attachment==null) {
			throw new AppException("common.notfoundfile");
		}
		response.setCharacterEncoding("utf-8");  
		response.addHeader("Content-type", attachment.getContentType());
        try {  
        	String fileName = new String(attachment.getFileName().getBytes("UTF-8"),"ISO8859_1");
        	response.setHeader("Content-Disposition", "attachment;fileName="+fileName);  
        	String path = request.getSession().getServletContext().getRealPath("/");
            File file=new File(path+attachment.getUrl());  
            InputStream inputStream=new FileInputStream(file);  
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  
            }  
            inputStream.close();  
            os.close();
            attachment.setFrequency(attachment.getFrequency()+1);
            attachmentService.update(attachment);
        } catch (FileNotFoundException e) {  
        	throw new AppException("common.notfoundfile");  
        } catch (IOException e) {  
        	throw new AppException("common.io");
        }  
		return null;
	}
	
	@Autowired
	public void setAttachmentService(AttachmentService attachmentService) {
		this.attachmentService = attachmentService;
	}
	
	
}
